﻿#include "PowerOutput.h"
#include "GlobalHeader.h"

PowerOutput *g_pPowerOutput = nullptr;
PowerOutputThread *g_pPowerOutputThread = nullptr;
bool g_bExit = false;

PowerOutput::PowerOutput(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
	g_pPowerOutput = this;
	m_bUpdateFlag = false;
	/*QSize size = ui.tableWidget_Log->horizontalHeaderItem(0)->sizeHint();
	size.setWidth(130);
	ui.tableWidget_Log->horizontalHeaderItem(0)->setSizeHint(size);*/
	ui.comboBox_Delay->setValidator(new QIntValidator);
	m_LogUpdateTimer.start(200);
//	ui.action_Dir->setIcon(QIcon(":/SiteDataSortTool/folderOpen.png"));
	connect(ui.action_File, &QAction::triggered, this, [=](bool)
	{
		const QString strFileName = QFileDialog::getOpenFileName(this, u8"请选择需要处理的文件","./Data","*.csv").toUtf8();
		if (strFileName.isEmpty() || !QFile::exists(strFileName))
			return;
		if (!g_pPowerOutputThread)
			g_pPowerOutputThread = new PowerOutputThread(nullptr);
		QString strDesIP = ui.lineEdit_DesIP->text();
		QHostAddress HostAddress(strDesIP);
		if (HostAddress.isNull())
		{
			gAddLog(LOGTYPE_ERROR, u8"信号源IP不合法:" + strDesIP);
			return;
		}
		g_pPowerOutputThread->PutFileToDeal(strFileName, ui.comboBox_Delay->currentText().toUInt());
		g_pPowerOutputThread->start();
		
	});

	connect(&m_LogUpdateTimer, &QTimer::timeout, this, [=]
	{
		if (!m_bUpdateFlag)
			return;
		do
		{
			tagLogInfo LogInfo = m_QueueLog.dequeue();
			int iRowIndex = ui.tableWidget_Log->rowCount();
			ui.tableWidget_Log->insertRow(iRowIndex);
			ui.tableWidget_Log->setItem(iRowIndex, 0, new QTableWidgetItem(LogInfo.strDt));
			ui.tableWidget_Log->setItem(iRowIndex, 1, new QTableWidgetItem(LogInfo.strType));
			ui.tableWidget_Log->setItem(iRowIndex, 2, new QTableWidgetItem(LogInfo.strLog));
		} while (!g_bExit && !m_QueueLog.isEmpty());
//		ui.tableWidget_Log->addItems(m_strListLog);
		m_bUpdateFlag = false;
//		m_strListLog.clear();
		ui.tableWidget_Log->scrollToBottom();
	});

	connect(this, &PowerOutput::signal_CloseNet, this, [=]
	{
		if (ui.pushButton_TCPConnect->text() == u8"关闭连接")
			emit ui.pushButton_TCPConnect->click();
	},Qt::QueuedConnection);
	connect(&m_TcpSocket, &QTcpSocket::disconnected, this, [=]()
	{
		QString strLog = u8"信号源控制网络断开连接!";
		//		strLog += m_TcpSocket.errorString();
		gAddLog(LOGTYPE_WARNING, strLog);
	});
	connect(&m_TcpSocket, &QTcpSocket::connected, this, [=]()
	{
		gAddLog(LOGTYPE_WARNING, u8"信号源控制网络连接成功!");
	});
	connect(&m_TcpSocket, static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error),
		[=](QAbstractSocket::SocketError socketError)
	{
		QString strLog = u8"信号源控制网络发生错误!";
		strLog += m_TcpSocket.errorString();
		gAddLog(LOGTYPE_WARNING, strLog);
	});
	AddLog(LOGTYPE_MESSAGE, u8"系统加载");
}

PowerOutput::~PowerOutput()
{
	g_bExit = true;
}

void PowerOutput::AddLog(LOGTYPE TYPE, const QString &strLog)
{
	tagLogInfo LogInfo;
	LogInfo.strDt = QDateTime::currentDateTime().toString("yyyyMMddHHmmsszzz");
	LogInfo.strLog = strLog;
	//写文件
	switch (TYPE)
	{
		case LOGTYPE_ERROR:
		{
			LogInfo.strType = u8"错误";
		}
		break;
		case LOGTYPE_WARNING:
		{
			LogInfo.strType = u8"警告";
		}
		break;
		case LOGTYPE_MESSAGE:
		{
			LogInfo.strType = u8"信息";
		}
		break;
		case LOGTYPE_DEBUG:
		{
			LogInfo.strType = u8"调试";
		}
		break;
		default:
		{
			LogInfo.strType = u8"未知";
		}
		break;
	}
	m_QueueLog.enqueue(LogInfo);
	//更新窗口
	m_bUpdateFlag = true;
}

void PowerOutput::SendCmd(const QString &strCmd)
{
	if (m_TcpSocket.state() == QAbstractSocket::ConnectedState)
	{
		m_TcpSocket.write(strCmd.toLatin1());
		bool bResult = m_TcpSocket.waitForBytesWritten(200);
		if (bResult)
		{
			QString strLog = "命令发送成功:";
			strLog += strCmd;
			gAddLog(LOGTYPE_MESSAGE, strLog);
		}
		else
		{
			QString strLog = "命令发送失败:";
			strLog += strCmd;
			gAddLog(LOGTYPE_ERROR, strLog);
		}
	}
	else
	{
		gAddLog(LOGTYPE_ERROR, u8"网络状态未连接，发送命令失败:" + strCmd);
	}
}

void PowerOutput::on_pushButton_TCPConnect_clicked()
{
	bool bConnected = false;
	if (ui.pushButton_TCPConnect->text() == u8"关闭连接")
	{
		m_TcpSocket.disconnectFromHost();
		bConnected = false;
	}
	else
	{
		QString strDesIP = ui.lineEdit_DesIP->text();
		QHostAddress HostAddress(strDesIP);
		if (HostAddress.isNull())
		{
			gAddLog(LOGTYPE_ERROR, u8"信号源IP不合法:" + strDesIP);
			return;
		}
		bConnected = InitTcpNet(HostAddress, ui.spinBox_DesPort->value());
	}
	ui.lineEdit_DesIP->setEnabled(!bConnected);
	ui.spinBox_DesPort->setEnabled(!bConnected);
	ui.pushButton_TCPConnect->setText(bConnected ? u8"关闭连接" : u8"打开连接");
}

void PowerOutput::on_pushButton_Output_clicked()
{
	QString strCmd = QString().sprintf(":FREQ %.0fHz\n", ui.doubleSpinBox_OutputFreq->value());
	SendCmd(strCmd);
	strCmd = QString().sprintf("POW:AMPL %.3fdbm\n", ui.doubleSpinBox_OutputPower->value());
	SendCmd(strCmd);
}

bool PowerOutput::InitTcpNet(const QHostAddress &HostAddress ,const quint16 usPort)
{
	m_TcpSocket.connectToHost(HostAddress, usPort);
	if (!m_TcpSocket.waitForConnected(1000))
	{
		QString strLog = u8"信号源控制网络连接失败," + m_TcpSocket.errorString();
		strLog += "IP:" + HostAddress.toString();
		strLog += "PORT:" + QString::number(usPort);
		gAddLog(LOGTYPE_ERROR, strLog);
		return false;
	}
	return true;
}
